package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.UserConstants.UserConstans;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        //判断参数
        if (authDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        authDto.checkParam();

        //分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper();
        if(authDto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,authDto.getStatus());
        }
        IPage pageParam = new Page(authDto.getPage(),authDto.getSize());
        IPage result = page(pageParam, wrapper);
        ResponseResult responseResult = new PageResponseResult(authDto.getPage(),authDto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    /**
     * 根据状态进行审核
     * @param dto
     * @param status
     * @return
     */
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查status
        if(checkStatus(status)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if(dto.getMsg() != null){
            apUserRealname.setBackImage(dto.getMsg());
        }
        updateById(apUserRealname);
        //3.如果审核状态是通过，创建自媒体账户，创建作者信息
        if(status.equals(UserConstans.PASS_AUTH)){
            ResponseResult result = createWmUserAndAuthor(dto);
            if(result != null){
                return result;
            }
        }
        //int i = 1/0;
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WmUserFeign wmUserFeign;
    //创建自媒体账户，创建作者信息
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //获取ap_user信息
        Integer apUserRealnameId = dto.getId();
        ApUserRealname apUserRealname = getById(apUserRealnameId);
        Integer userId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询当前有没有自媒体账号
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        //创建自媒体账户
        if(wmUser == null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wmUserFeign.save(wmUser);
        }
        //创建作者
        createAuthor(wmUser);
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);
        return null;
    }

    @Autowired
    ArticleFeign articleFeign;
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findByUserId(apUserId);
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setType(UserConstans.AUTH_TYPE);
            articleFeign.save(apAuthor);
        }
    }


    //检查status
    private boolean checkStatus(Short status) {
        if(status == null ||(!status.equals(UserConstans.FAIL_AUTH)) && (!status.equals(UserConstans.PASS_AUTH))){
            return true;
        }
        return false;
    }
}
